package com.deng.shiro;

import cn.hutool.json.JSONUtil;
import com.deng.common.lang.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//自定义过滤器处理ajax请求
public class AuthFilter extends UserFilter {
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        //判断请求是否时ajax请求，是的话就弹窗，url请求重定向到登录页面
        HttpServletRequest httpServletRequest=(HttpServletRequest) request;
        // ajax 弹窗显示未登录
        String header = httpServletRequest.getHeader("X-Requested-With");
        if(header != null  && "XMLHttpRequest".equals(header)) {
            //判断当前用户是否登录
            boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
            //未登录返回json数据
            if(!authenticated) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSONUtil.toJsonStr(Result.fail("请先登录！")));
            }
        } else {
            // web 重定向到登录页面
            super.redirectToLogin(request, response);
        }
    }
}
